package com.usc.pys7.controllers;

import com.usc.pys7.module.Student;
import com.usc.pys7.service.StudentService;
import com.usc.pys7.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentServiceImpl studentServiceImpl;

    @GetMapping(value = "/find/{id}")
    public ResponseEntity<ResponseResult> findById (@PathVariable("id") Integer id) {
       Student s = studentService.get(id);
       if(s == null){
           return ResponseEntity.ok(ResponseResult.error("查无此id号学生"));
       }
       return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }
    @PostMapping(value = "/add")
    public ResponseEntity<ResponseResult> add( Student s) {

          System.out.println(s);
          s=studentService.add(s);
          boolean b=true;
          if(!b){
              return ResponseEntity.ok(ResponseResult.error("添加失败"));
          }
          return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }
    @PutMapping(value = "/update")
    public ResponseEntity<ResponseResult> update( Student s) {
     s=studentService.update(s);
     boolean b=true;
     if(!b){
         return ResponseEntity.ok(ResponseResult.error("更新失败"));
     }
     return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }
   @GetMapping(value = "/findByName")
    public ResponseEntity<ResponseResult<List<Student>>> findByName(@RequestParam(value = "name",required = false) String name) {
        List<Student> list=studentService.findByName(name);
        ResponseResult rr=ResponseResult.ok().setData(list);
        return ResponseEntity.ok(rr);
   }
   @DeleteMapping(value = "/delete/{id}")
    public ResponseEntity<ResponseResult<Student>> deleteById(@PathVariable("id") Integer id) {
     studentService.delete(id);
     return ResponseEntity.ok(ResponseResult.ok("删除编号为："+id+"的学生"));
     }
}